package controllers

import (
	"encoding/json"
	"github.com/beego/beego/v2/adapter/validation"
	beego "github.com/beego/beego/v2/server/web"
	"path/filepath"
	"store/models"
	"strconv"
	"strings"
	"time"
)

type StoreController struct {
	beego.Controller
}

func (c *StoreController) Add() {
	name := c.GetString("name")
	img := c.GetString("img")
	status := c.GetString("status")
	starttime := c.GetString("starttime")
	endtime := c.GetString("endtime")
	tel := c.GetString("tel")
	address := c.GetString("address")
	info := c.GetString("info")
	store := models.Store{
		Name:      name,
		Img:       img,
		Status:    status,
		Starttime: starttime,
		Endtime:   endtime,
		Tel:       tel,
		Address:   address,
		Info:      info,
	}
	valid := validation.Validation{}
	validation.SetDefaultMessage(map[string]string{
		"Required": "数据不能为空",
	})
	_, err := valid.Valid(&store)
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "验证错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if valid.HasErrors() {
		for _, err = range valid.Errors {
			c.Data["json"] = JsonRes{
				Code: 500,
				Msg:  err.Error(),
				Data: nil,
			}
			c.ServeJSON()
		}
	}
	//models.DB.Begin()
	err = models.DB.Create(&store).Error
	if err != nil {
		//models.DB.Rollback()
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		//models.DB.Commit()
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *StoreController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "请上传文件",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	if header.Size > 5*1024*1024 {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "文件过大，不得操作5M",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	ext := strings.ToLower(filepath.Ext(header.Filename))
	allowExt := map[string]bool{
		".png":  true,
		".jpeg": true,
	}
	if !allowExt[ext] {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "文件格式错误，必须是png，jpeg格式",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		imgUrl := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "上传成功",
			Data: imgUrl,
		}
		c.ServeJSON()
	}
}
func (c *StoreController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 10)
	key := "store-" + strconv.Itoa(page)
	val, err := models.Rdb.Get(key).Result()
	pageData := make(map[string]interface{})
	if err != nil {
		var count int64
		err = models.DB.Model(&models.Store{}).Count(&count).Error
		if err != nil {
			c.Data["json"] = JsonRes{
				Code: 500,
				Msg:  "总数查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
		offset := (page - 1) * size
		var store []models.Store
		err = models.DB.Debug().Offset(offset).Limit(size).Find(&store).Error
		pageData["count"] = count
		pageData["store"] = store
		if err != nil {
			c.Data["json"] = JsonRes{
				Code: 500,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			marshal, _ := json.Marshal(&pageData)
			value := string(marshal)
			models.Rdb.Set(key, value, time.Second*10)
			c.Data["json"] = JsonRes{
				Code: 200,
				Msg:  "查询成功-mysql",
				Data: pageData,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "详情查询成功-redis",
			Data: pageData,
		}
		c.ServeJSON()
	}

}
func (c *StoreController) Info() {
	id, _ := c.GetInt("id")
	RankKey := "Rank"
	models.Rdb.ZIncrBy(RankKey, 1, strconv.Itoa(id))
	key := "store-" + strconv.Itoa(id)
	val, err := models.Rdb.Get(key).Result()
	var store models.Store
	if err != nil {
		err = models.DB.Model(&models.Store{}).Where("ID=?", id).First(&store).Error
		if err != nil {
			c.Data["json"] = JsonRes{
				Code: 500,
				Msg:  "详情展示失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
		jsonByte, _ := json.Marshal(store)
		value := string(jsonByte)
		models.Rdb.Set(key, value, 0)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "mysql-详情展示成功",
			Data: store,
		}
		c.ServeJSON()
	} else {
		json.Unmarshal([]byte(val), store)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "redis-详情展示成功",
			Data: store,
		}
		c.ServeJSON()
	}

}
func (c *StoreController) Up() {
	name := c.GetString("name")
	img := c.GetString("img")
	status := c.GetString("status")
	starttime := c.GetString("starttime")
	endtime := c.GetString("endtime")
	tel := c.GetString("tel")
	address := c.GetString("address")
	info := c.GetString("info")
	id, _ := c.GetInt("id")
	store := models.Store{
		Name:      name,
		Img:       img,
		Status:    status,
		Starttime: starttime,
		Endtime:   endtime,
		Tel:       tel,
		Address:   address,
		Info:      info,
	}
	err := models.DB.Where("ID=?", id).Updates(&store).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *StoreController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Store{}, id).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		key := "store-" + strconv.Itoa(id)
		models.Rdb.Del(key)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *StoreController) Rank() {
	key := "Rank"
	rank, err := models.Rdb.ZRevRange(key, 0, 10-1).Result()
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "排行榜获取失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var stores []models.Store
	for _, s := range rank {
		var store models.Store
		err = models.DB.Model(&models.Store{}).Where("ID=?", s).First(&store).Error
		if err != nil {
			break
		}
		stores = append(stores, store)
	}
	c.Data["json"] = JsonRes{
		Code: 200,
		Msg:  "展示成功",
		Data: stores,
	}
	c.ServeJSON()
}
